import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const User2PostSchema = new mongoose.Schema({
    userId: String,
    postId: String,
    createTime: Number
});

User2PostSchema.methods.saveUser2Post = function (user2Post, cb) {
    user2Post.createTime = moment().unix();
    this.model('user2Post').insertMany([user2Post], cb);
};

User2PostSchema.methods.getUser2Posts = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const user2PostModel = this.model('user2Post');
    user2PostModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        user2PostModel.find(leftQuery, { passwd: 0 }).skip((current - 1) * pageSize).limit(pageSize).exec((err, user2Posts) => cb(err, user2Posts, count, hasMore));
    });
};

User2PostSchema.methods.getAllUser2Posts = function (query, cb) {
    this.model('user2Post').find(query, { postId: 1, _id: 0 }, cb);
};

User2PostSchema.methods.getUser2Post = function (query, cb) {
    this.model('user2Post').findOne(query, cb);
};

User2PostSchema.methods.updateUser2Post = function (user2Post, cb) {
    const _id = user2Post._id;
    delete user2Post._id;
    this.model('user2Post').findOneAndUpdate({ _id }, { $set: user2Post }, cb);
};

User2PostSchema.methods.removeUser2Posts = function (user2PostIds, cb) {
    this.model('user2Post').remove({ _id: { $in: user2PostIds } }, cb);
};

export default db.model('user2Post', User2PostSchema);